package com.uyayo.ucenter.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uyayo.framework.common.exception.EmailMultipleException;
import com.uyayo.framework.common.exception.PhoneMultipleException;
import com.uyayo.framework.common.exception.UserMultipleException;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.pagehelper.pojo.OrderBy;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.util.OrderByUtil;
import com.uyayo.ucenter.entity.Member;
import com.uyayo.ucenter.entity.MemberGroupRelation;
import com.uyayo.ucenter.entity.MemberState;
import com.uyayo.ucenter.mapper.MemberGroupRelationMapper;
import com.uyayo.ucenter.mapper.MemberMapper;
import com.uyayo.ucenter.mapper.MemberStateMapper;
import com.uyayo.ucenter.model.MemberCondition;
import com.uyayo.ucenter.service.MemberService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service("memberService")
public class MemberServiceImpl implements MemberService {

	private final MemberMapper memberMapper;
	private final MemberStateMapper memberStateMapper;
	private final MemberGroupRelationMapper memberGroupRelationMapper;

	public MemberServiceImpl(MemberMapper memberMapper, MemberStateMapper memberStateMapper, MemberGroupRelationMapper memberGroupRelationMapper) {
		this.memberMapper = memberMapper;
		this.memberStateMapper = memberStateMapper;
		this.memberGroupRelationMapper = memberGroupRelationMapper;
	}


	//@Cacheable(value = "getMemberById",key="#id")
	@Override
	public Member getMemberById(Long id){
		return memberMapper.selectByPrimaryKey(id);
	}

	@Override
	public Member getMemberByEmail(String email) {
		Member member = new Member();
		member.setEmail(email);
		return memberMapper.selectOne(member);
	}

	@Override
	public List<Member> selectMember(MemberCondition memberCondition) {
		Example example = new Example(Member.class);
		example.createCriteria();
		return memberMapper.selectByExample(example);
	}
	
	@Override
	public PageBean<Member> selectMemberByPaging(PageBean<Member> pageBean,MemberCondition memberCondition) {

		List<Member> userList;
		//分页处理
		List<OrderBy> orderByList = new ArrayList<>();
		orderByList.add(new OrderBy("createTime", "create_time"));
		orderByList.add(new OrderBy("updateTime", "update_time"));

		OrderByUtil  orderByUtil = new OrderByUtil();
		String orderBy = orderByUtil.getOrderBy(orderByList, pageBean.getOrderField(), pageBean.getOrderDirection());
		PageHelper.startPage(pageBean.getPageCurrent(), pageBean.getPageSize());
		
		Example example = new Example(Member.class);
		if(!StringUtils.isEmpty(orderBy)){
			example.setOrderByClause(orderBy);
		}
		Criteria criteria = example.createCriteria();
		if(!StringUtils.isEmpty(memberCondition.getUsername())){
			criteria.andLike("username","%"+memberCondition.getUsername()+"%");
		}
		if(memberCondition.getBeginCreateTime()!=null || memberCondition.getEndCreateTime()!=null){
			criteria.andBetween("createTime", memberCondition.getBeginCreateTime(), memberCondition.getEndCreateTime());
		}
		userList = memberMapper.selectByExample(example);

		//取记录总条数
		PageInfo<Member> pageInfo = new PageInfo<>(userList);
		pageBean.setTotalCount(pageInfo.getTotal());
		pageBean.setList(userList);
		return pageBean;
	}
	

	@Override
	public int saveMember(Member member,MemberState memberState) throws UserMultipleException,EmailMultipleException, PhoneMultipleException {
		Member memberTest = getMemberByUsername(member.getUsername());
		if(memberTest!=null){
			throw new UserMultipleException("User multiple error!");
		}
		Member memberEmailTest = getMemberByEmail(member.getEmail());
		if(memberEmailTest!=null){
			throw new EmailMultipleException("Email multiple error!");
		}
		Member memberPhoneTest = getMemberByPhone(member.getPhone());
		if(memberPhoneTest!=null){
			throw new PhoneMultipleException("Phone multiple error!");
		}
		int insertCount = memberMapper.insertSelective(member);
		if(insertCount>0){
			Member memberNew = getMemberByUsername(member.getUsername());
			if(memberNew!=null){
				memberState.setRegisterTime(new Date());
				memberState.setCreateTime(new Date());
				memberState.setMemberId(memberNew.getId());
				memberStateMapper.insertSelective(memberState);
			}
		}
		return insertCount;
	}

	@Override
	public Member getMemberByPhone(String phone) {
		Member member = new Member();
		member.setPhone(phone);
		return memberMapper.selectOne(member);
	}

	@Override
	public int updateMember(Member member) throws UserMultipleException, EmailMultipleException, PhoneMultipleException {
		Member memberTest = getMemberByUsername(member.getUsername());
		if(memberTest!=null && !Objects.equals(member.getId(),memberTest.getId())){
			throw new UserMultipleException("Email multiple error!");
		}
		Member memberEmailTest = getMemberByEmail(member.getEmail());
		if(memberEmailTest!=null && !Objects.equals(member.getId(),memberEmailTest.getId())){
			throw new EmailMultipleException("Email multiple error!");
		}
		Member memberPhoneTest = getMemberByPhone(member.getPhone());
		if(memberPhoneTest!=null && !Objects.equals(member.getId(),memberPhoneTest.getId())){
			throw new PhoneMultipleException("Phone multiple error!");
		}
		return memberMapper.updateByPrimaryKeySelective(member);
	}

	@Override
	public int deleteMember(Long id) {
		return memberMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Result saveMemberGroupRelation(String ids,Long memberId) {
		Result customResult = new Result(200,"保存成功");

		String[] idArr = ids.split(",");
		
		List<MemberGroupRelation> memberGroupRelationList = new ArrayList<>();
		if(idArr.length>0 && !idArr[0].equals("")){
			for (String id : idArr) {
				MemberGroupRelation memberGroupRelation = new MemberGroupRelation();
				memberGroupRelation.setMemberId(memberId);
				memberGroupRelation.setGroupId(Long.valueOf(id));
				memberGroupRelationList.add(memberGroupRelation);
			}
		}
		int deleteCount;
		int saveCount = 0;
		try {
			Example example = new Example(MemberGroupRelation.class);
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo("memberId", memberId);
			deleteCount = memberGroupRelationMapper.deleteByExample(example);
			if(memberGroupRelationList.size()>0){
				saveCount = memberGroupRelationMapper.insertMemberGroupRelationByList(memberGroupRelationList);
			}
			customResult.setMessage("删除"+deleteCount+"条记录，保存"+saveCount+"条记录！");

		} catch (Exception e) {
			customResult=Result.build(500, "保存失败！");
			e.printStackTrace();
		}
		return customResult;
	}
	
	@Override
	public Member getMemberByUsername(String username) {
		Member member = new Member();
		member.setUsername(username);
		return memberMapper.selectOne(member);
	}
	
}
